package com.itelite.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@Slf4j
public class FileUtils {
    public static final Set<String> imageExtensionName;
    public static final Set<String> zipExtensionName;
    static {
        imageExtensionName = new HashSet<>();
        imageExtensionName.add("image/png");
        imageExtensionName.add("image/jpeg");
        zipExtensionName = new HashSet<>();
        zipExtensionName.add("application/zip");
        zipExtensionName.add("application/x-7z-compressed");
    }

    public static File createGroupDir(String parentDir,String groupName){
        //创建父级文件夹（file=组名/月份/随机文件名/）
//        String root = System.getProperty("user.dir");
//        File parent = new File(root,parentDir);
//        if(!parent.exists()) parent.mkdirs();
        File group = new File(createDir(parentDir), groupName);
        if(!group.exists()) group.mkdirs();
        File year =  new File(group, Calendar.getInstance().get(Calendar.YEAR)+"");
        if(!year.exists()) year.mkdirs();
        return year;
    }
    public static File createDir(String parentDir){
        //创建父级文件夹（file=组名/月份/随机文件名/）
        String root = System.getProperty("user.dir");
        File parent = new File(root,parentDir);
        if(!parent.exists()) parent.mkdirs();
        return parent;
    }


    //创建唯一名称
    public static String createFileName(String fn) {
        log.info("FN:"+fn);
        //月份-UUID
        return (Calendar.getInstance().get(Calendar.MONTH)+1)+"-"+UUID.randomUUID().toString()+fn.substring(fn.lastIndexOf('.'));
    }
    //
    public static String createIconName(String fn) {
        return UUID.randomUUID().toString()+fn.substring(fn.lastIndexOf('.'));
    }
    public static String getExtensionName(MultipartFile file){
        String originalFileName = file.getOriginalFilename();
        assert originalFileName != null;
        return originalFileName.substring(originalFileName.lastIndexOf('.'));
    }

    public static boolean validateFilesExtensionName(MultipartFile[] files, Set<String> extensionName) {
        boolean flag = false;
        for (int i = 0; i < files.length; i++) {
            if (!extensionName.contains(files[i].getContentType())) {
                files[i]=null;
            }else flag = true;
        }
        return flag;
    }
    public static boolean validateFilesExtensionNameForImage(MultipartFile...files) {
        if(files==null) return false;
        return validateFilesExtensionName(files,imageExtensionName);
    }
    public static void validateFilesExtensionNameForZip(MultipartFile... files) {
        if(files==null) return;
        validateFilesExtensionName(files,zipExtensionName);
    }

    public static String getFileName(String s) {
       return s.substring(s.lastIndexOf('/')+1,s.lastIndexOf('.'));
    }
}
